const Payment = require("../models/Payment");
const request = require("../utils/request");

class paymentService {
  // 统一下单
  async unifiedOrder(paymentInfo) {
    try {
      const xmlData = `
      <xml>
        <appid>wxd930ea5d5a258f4f</appid>
        <mch_id>10000100</mch_id>
        <device_info>1000</device_info>
        <body>test</body>
        <nonce_str>ibuaiVcKdpRxkhJA</nonce_str>
        <out_trade_no>1234567890</out_trade_no>
        <trade_type>JSAPI</trade_type>
        <total_fee>100</total_fee>
        <notify_url>https://example.com/notify</notify_url>
        <sign>9A0A8659F005D6984697E2CA0A9CF3B7</sign>
      </xml>
      `;
      const res = await request.request({
        method: "POST",
        url: "https://api.mch.weixin.qq.com/pay/unifiedorder",
        data: xmlData,
        headers: {
          "Content-Type": "text/xml",
        },
      });
      // console.log(res); 'https://api.mch.weixin.qq.com/pay/unifiedorder', paymentInfo
      return res;
    } catch (error) {
      throw new Error("创建订单失败");
    }
  }

  // 统一下单v3
  async unifiedOrderV3({ mchid, out_trade_no, appid, description, notify_url, amount, openid }) {
    try {
      const data = {
        mchid: "1900006XXX",
        out_trade_no: "1217752501201407033233368318",
        appid: "wxdace645e0bc2cXXX",
        description: "Image形象店-深圳腾大-QQ公仔",
        notify_url: "https://www.weixin.qq.com/wxpay/pay.php",
        amount: {
          total: 1,
          currency: "CNY",
        },
        payer: {
          openid: "o4GgauInH_RCEdvrrNGrntXDuXXX",
        },
      };

      const res = await request.post('https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi', data)
      return res
    } catch (error) {
      throw new Error("创建订单失败~");
    }
  }
}

module.exports = new paymentService();
